<template>
  <a-spin size="large" tip="数据处理中，请耐心等待……" :spinning="loading">
    <a-card class="layout-card">
      <table class="topClose" width="100%">
        <thead>
          <tr>
            <th colspan="4">
              科目代码:
              <span v-if="userInfo.manageKmdm != '0'">
                {{ `${chartObj.kmdm}(${chartObj.kmmc})` }}
              </span>
              <a-select
                v-else
                :filter-option="filterOption"
                allowClear
                v-model:value="Data.pageAccountCodeKmdm"
                :options="kmOptions"
                :field-names="{ label: 'kmmc', value: 'kmdm' }"
                show-search
                style="width: 200px"
                placeholder="请选择科目"
              />
            </th>
            <th colspan="2">
              学院名称: {{ chartObj.xymc ? `${chartObj.xydm}(${chartObj.xymc})` : '--' }}
            </th>
            <!-- <th colspan="2">试题结构</th> -->
            <th>异常标识数</th>
            <th>科目评阅阶段</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style="color: #d43030; font-size: 16px; font-weight: 600">试卷类型</td>
            <td>科目总分</td>
            <td>科目组长</td>
            <td>评阅教师数</td>
            <td>学院管理员</td>
            <td>学院教师数</td>
            <!-- <td>大题数</td>
            <td>已建子集题目</td> -->
            <td rowspan="2" v-if="abnormalToTle > 0">
              <span style="font-size: 18px; font-weight: 600; color: #d43030">
                {{ abnormalToTle }}
              </span>
              条
            </td>
            <td rowspan="2" v-else> 无 </td>
            <td rowspan="2" style="font-size: 18px; font-weight: 600; color: #d43030">
              {{ statusEnum[chartObj.kmpyjd] }}
            </td>
          </tr>
          <tr>
            <td>{{ sjlbList.find(item => item.value == chartObj.sjlb)?.label }}</td>
            <td>{{ chartObj.kmzf }}</td>
            <td> {{ chartObj.pyzzName }}</td>
            <td> {{ chartObj.kfpjsrs }}人</td>
            <td> {{ chartObj.xyglyName }}</td>
            <td> {{ chartObj.xyJszys }}人</td>
          </tr>
        </tbody>
      </table>

      <a-row align="middle" justify="space-between">
        <a-col>
          <a-button
            :disabled="statuTypeBloon || !Data.pageAccountCodeKmdm || !chartObj.sjlb"
            type="primary"
            @click="releaseFun"
          >
            发布试卷
          </a-button>

          <a-button
            class="ml-8px"
            type="primary"
            @click="modifyStructure"
            :disabled="!Data.pageAccountCodeKmdm || !chartObj.sjlb"
            v-if="userInfo.accountType == 'ADMIN'"
          >
            修改试题结构
          </a-button>
        </a-col>
      </a-row>

      <div class="claserbox">
        <a-row align="middle" justify="space-between">
          <a-col :span="6">
            <div class="infobox infoleft pb-0">
              <div class="treebox" ref="treeReefbox">
                <a-tree
                  :tree-data="list || []"
                  :fieldNames="{ children: 'children', title: 'tmbt', key: 'id' }"
                  :blockNode="true"
                  checkable
                  :key="Data.treeHeigh"
                  :height="Data.treeHeigh"
                  v-model:checkedKeys="checkedKeys"
                  checkStrictly
                  @select="treeSelect"
                >
                  <template #title="record">
                    <div class="flex justify-between">
                      <span>
                        {{ record.tmbh }}{{ record.tmbt }} ({{
                          record.mkmc ? record.mkmc : record.tmlx
                        }})
                      </span>
                      <a-tooltip
                        :key="'#fadfvf'"
                        :title="record.handlTip ? record.handlTipMsg : '已完成'"
                        :color="'#fadfvf'"
                      >
                        <a-button
                          :danger="record.handlTip"
                          type="link"
                          :class="record.handlTip ? '' : '!text-green-500'"
                        >
                          <ExclamationCircleOutlined v-if="record.handlTip" />
                          <CheckCircleOutlined v-else />
                        </a-button>
                      </a-tooltip>
                    </div>
                  </template>
                </a-tree>
              </div>
              <a-button
                class="allbutton"
                :disabled="statuTypeBloon || !Data.pageAccountCodeKmdm"
                size="small"
                danger
                @click="resetPySzbzCDaail"
              >
                重置评阅标准
              </a-button>
              <a-button
                class="allbutton"
                :disabled="!'TEST,FORMAL'.includes(chartObj.kmpyjd)"
                danger
                size="small"
                v-if="
                  userInfo.accountType == 'ADMIN' ||
                  userInfo.accountType == 'MANGER' ||
                  userInfo.accountType == 'XY'
                "
                @click="resetPyPlanDaail"
              >
                重置评阅进度
              </a-button>
              <br />
              <!-- <span class="text-[12px] text-dark-50">
              注:重置评阅进度/重置评阅标准只可以以最小评阅设置维度为维度进行操作
            </span> -->
            </div>
          </a-col>
          <a-col :span="18">
            <div class="infobox">
              <topicInfo
                v-model:treedataObj="treedataObj"
                :statuTypeBloon="statuTypeBloon"
                :kmdm="Data.pageAccountCodeKmdm"
                @successFun="successFun"
                @addChilNew="AddChilNew"
                @revocation="handelRevocation"
                @funTeacher="handelTeacher"
              />
            </div>
          </a-col>
        </a-row>
      </div>

      <!-- 其他操作 -->

      <editInfo
        v-model:other-showble="Data.otherShowble"
        v-model:isBatchHasObj="Data.isBatchHasObj"
        :chartObj="chartObj"
        :kmdm="Data.pageAccountCodeKmdm"
        @successFun="successFun"
        :sysConfig="sysConfig"
        v-if="Data.otherShowble"
      />

      <!-- 教师设置 -->

      <assignTeachers
        v-model:teacher-showble="Data.teacherShowble"
        v-model:isBatchHasObj="Data.isBatchHasObj"
        v-if="Data.teacherShowble"
        :kmdm="Data.pageAccountCodeKmdm"
        @successFun="successFun"
      />

      <!-- 新增子题弹窗 -->
      <addchildren
        v-model:addShowblePop="addShowblePop"
        :kmdm="Data.pageAccountCodeKmdm"
        :isBatchHasObj="treedataObj"
        @success="addSuccess"
      />
    </a-card>
  </a-spin>
</template>

<script setup lang="ts" name="AbnormalTeacher">
import { onMounted, ref, h, computed, watch, reactive, onActivated, onUnmounted } from 'vue'
import { useList } from '/@/hooks/web/useList'

onActivated(() => {
  if (!!Data.pageAccountCodeKmdm && Data.pageAccountCodeKmdm !== '0') {
    defaultFilterOption.kmdm = Data.pageAccountCodeKmdm
    getRelseFun()
  }
  window?.addEventListener('resize', resize)
  setTimeout(() => {
    resize()
  }, 100)
})

onUnmounted(() => {
  window?.removeEventListener('resize', resize)
})

// 各个弹窗组件以及其他组件
import assignTeachers from './components/assignTeachers.vue'
import topicInfo from './components/topicInfo.vue'
import editInfo from './components/edit.vue'
import addchildren from './components/addchildren.vue'
// 判断是否是机读题
import { isJdCorrectType } from './index'
import { statusEnum } from '/@/enums/privateEnums'

import {
  getAbnormityTeacher,
  getAbnorOpublishSjByKmdm,
  getAcountmdm,
  resetPySzbzCkdaBzDaail,
  resetPyProcess,
} from '/@/api/examinationAudit'
import { getKmSimpAlleList } from '/@/api/organization/subjectManage'
// 消息提示框
import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage, createConfirm } = useMessage()
// 本地存储
import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const userInfo = <any>computed(() => userStore.getUserInfo)

const Data = reactive<any>({
  isBatchHasObj: {},
  teacherShowble: false,
  otherShowble: false,
  pageAccountCodeKmdm: null,
  addShowblePop: false,
  treeHeigh: 100,
})

const treeReefbox = ref<any>(null)

function resize() {
  Data.treeHeigh = treeReefbox.value?.offsetHeight
}

/**
 * 子级是否包含其他类型的新增题目类型
 */
const getIsBatchHasObj = (data: any = []) => {
  let isBatchHasObj: any = true
  for (let i = 0; i < data.length; i++) {
    if (data[i].children && data[i].children.length) {
      isBatchHasObj = getIsBatchHasObj(data[i].children)
    }
    if (!data[i].customFlag || data[i].customType !== 'PYZZ' || !isBatchHasObj) {
      return false
    }
  }
  return isBatchHasObj
}

// 选择树节点触法
//选中的树节点对象
const treedataObj: any = ref({})
const treeSelect = ({}, e) => {
  let row = e.node.dataRef || {}
  if (
    e.selected &&
    (((row.tmlx == '填空题' || isJdCorrectType(row)) &&
      ((row.children && row.children.length && row.children[0]?.sfzxdtdw) || row?.sfzxdtdw)) ||
      (row.tmlx !== '填空题' &&
        !isJdCorrectType(row) &&
        (!row.children || row.children?.length == 0 || getIsBatchHasObj(row.children))))
  ) {
    treedataObj.value = row
  } else {
    treedataObj.value = {}
  }
}
// 选中状态

const { list, loadData, defaultFilterOption, reset } = <any>useList(getAbnormityTeacher, {
  defaultFilterOption: <any>{
    kmdm: Data.pageAccountCodeKmdm,
    pySzInfoFlag: true,
  },
  immediate: false,
  requestSuccess: (result: any) => {
    if (result.code != 200) {
      createMessage.error(result.message)
    }
  },
})

// 待处理异常数量
const abnormalToTle = computed(() => {
  let num = 0
  if (list.value?.length) {
    return arrangeabnormal(list.value)?.num
  }
  return num
})

// 判断是否设置评阅标准
const arrangeabnormal = arr => {
  let num = 0
  let subTmfzAll = 0
  for (let i = 0; i < arr.length; i++) {
    let record = arr[i]
    if (!record.handlTip) {
      record.handlTip = false
    }
    if (record.children && record.children.length) {
      // 判断子题是否设置评阅模式
      let { num: childrenNum, subTmfzAll: number } = arrangeabnormal(record.children)
      num += childrenNum
      if (childrenNum > 0) {
        record.handlTip = true
        record.handlTipMsg = '子题评阅标准设置不完整。'
        num += 1
      }
      // 判断子题分数和是否和父题分数相等
      if (number != +record.tmfz) {
        record.handlTip = true
        record.handlTipMsg = '子题目分值和与父题目分值不相等。'
        num += 1
      }
      if (
        (isJdCorrectType(record) || record.tmlx === '填空题') &&
        record.children[0].sfzxdtdw &&
        record.sfwmk == 0
      ) {
        if (
          !record.pySzInfoVO?.pySzCkdaList.length ||
          record.pySzInfoVO?.pySzCkdaList.length != record.children.length
        ) {
          record.handlTip = true
          record.handlTipMsg = '参考答案设置不完整'
          num += 1
          for (let j = 0; j < record.children.length; j++) {
            if (
              record.pySzInfoVO?.pySzCkdaList.find(item => item.stId == record.children[j].id) ||
              (!record.pySzInfoVO?.pySzCkdaList && !record.pySzInfoVO?.pySzCkdaList.length)
            ) {
              record.children[j].handlTip = true
              record.children[j].handlTipMsg = '未设置参考答案'
            }
          }
        } else if (!record.pySzInfoVO?.pySzJsfpList.length) {
          record.handlTip = true
          record.handlTipMsg = '试题还未分配评阅教师'
          num += 1
        }
      } else if (record.tmlx != '填空题') {
        //非机读题设置情况
        record.disableCheckbox = true // 禁用选择框
      }
    } else if (!isJdCorrectType(record) && record.tmlx != '填空题') {
      // 非机读题设置情况
      if (!record.pySzInfoVO?.zpFc) {
        record.handlTip = true
        record.handlTipMsg = '复评分差不能为空。'
        num += 1
      } else if (!record.pySzInfoVO?.pySzCkdaList.length) {
        record.handlTip = true
        record.handlTipMsg = '试题还未设置参考答案'
        num += 1
      } else if (!record.pySzInfoVO?.pySzJsfpList.length) {
        record.handlTip = true
        record.handlTipMsg = '试题还未分配评阅教师'
        num += 1
      } else if (!record.tmfz) {
        record.handlTip = true
        record.handlTipMsg = '题目得分不能为空'
        num += 1
      } else if (!record.pySzInfoVO?.pydfgc) {
        record.handlTip = true
        record.handlTipMsg = '最小得分单位不能为空'
        num += 1
      } else if (+record.pySzInfoVO?.zpFc > +record.tmfz) {
        record.handlTip = true
        record.handlTipMsg = '自评允许最大分差(含)大于试题分值。'
        num += 1
      } else if (record.pySzInfoVO?.pyMs == '2' && +record.pySzInfoVO?.spFc > +record.tmfz) {
        record.handlTip = true
        record.handlTipMsg = '双评分差大于试题分值。'
        num += 1
      } else if (+record.pySzInfoVO?.pydfgc % 0.5) {
        record.handlTip = true
        record.handlTipMsg = '最小得分单位不是0.5的整数倍。'
        num += 1
      } else if (record.tmfz % +record.pySzInfoVO?.pydfgc) {
        record.handlTip = true
        record.handlTipMsg = '试题分值不是最小得分单位的整数倍。'
        num += 1
      } else if (record.pySzInfoVO?.pyMs == '2' && record.pySzInfoVO?.existsPyFpjsCount < 2) {
        record.handlTip = true
        record.handlTipMsg = '双评模式下至少分配两名教师'
        num += 1
      } else if (record.pySzInfoVO?.pyDfdXqList && record.pySzInfoVO?.pyDfdXqList.length) {
        let number = 0
        for (let j = 0; j < record.pySzInfoVO?.pyDfdXqList.length; j++) {
          if (record.pySzInfoVO?.pyDfdXqList[j].dfdScore % +record.pySzInfoVO?.pySzInfoVO?.pydfgc) {
            record.handlTip = true
            record.handlTipMsg = '试题得分点分值不能被最小得分单位整除。'
            num += 1
            break
          }
          number += +record.pySzInfoVO?.pyDfdXqList[j].dfdScore
        }
        if (number != record.tmfz) {
          record.handlTip = true
          record.handlTipMsg = '试题得分点的分值和试题的分值不相等。'
          num += 1
        }
      } else if (!record.pySzInfoVO?.pyMs) {
        record.handlTip = true
        record.handlTipMsg = '试题未设置评阅模式'
        num += 1
      }
    } else {
      //非机读题设置情况
      record.disableCheckbox = true // 禁用选择框
    }
    if (record.sfwmk == '1') {
      record.disableCheckbox = true // 禁用选择框
    }
    subTmfzAll += record.tmfz
  }
  return {
    subTmfzAll,
    num,
  }
}

// 设置答案成功回调方法
function successFun() {
  loadData() //从新获取试题结构数据;
  treedataObj.value.key = +new Date() //更新key值，重新渲染树;
}

const loading = ref(false)

// 发布试卷
const releaseFun = async () => {
  if (abnormalToTle.value > 0)
    return createMessage.error(`评阅标准存在${abnormalToTle.value}处异常，请修改评阅标准`)
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () => h('span', '确认发布试卷吗？'),
    onOk: () => {
      puthFun()
    },
  })
}

async function puthFun() {
  loading.value = true
  try {
    let { code, message } = await getAbnorOpublishSjByKmdm({
      kmdm: Data.pageAccountCodeKmdm,
    })
    if (code == 200) {
      createMessage.info('试卷已发布')
      getRelseFun()
    } else {
      createMessage.error(message)
    }
  } catch (err) {
    console.log(err)
  }

  loading.value = false
}

// 新增子题集 （改版）
const addShowblePop: any = ref(false)
const AddChilNew = () => {
  addShowblePop.value = true
}

// 新增子题集成功回调方法
function addSuccess() {
  loadData() //从新获取试题结构数据;
  treedataObj.value.key = +new Date() //更新key值，重新渲染树;
  addShowblePop.value = false
}

/**
 * 重置评阅标准
 */
const checkedKeys = ref<any>({})
const resetPySzbzCDaail = () => {
  if (checkedKeys.value?.checked?.length == 0 || !chartObj.value?.kmdm)
    return createMessage.error('请选择要重置评阅标准的试题')
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () =>
      h(
        'span',
        '将删除被选中试题的所有设置的评阅标准，得分点，参考答案等,且会终止评阅状态是否继续？'
      ),
    onOk: async () => {
      let { code, message } = await resetPySzbzCkdaBzDaail({
        kmdm: Data.pageAccountCodeKmdm,
        resetAllFlag: false,
        stIdList: checkedKeys.value.checked,
      })
      if (code === 200) {
        createMessage.info('重置成功')
        checkedKeys.value.checked = []
        getRelseFun()
      } else {
        createMessage.error(message)
      }
    },
  })
}
/**
 * 重置评阅进度
 */
const resetPyPlanDaail = () => {
  if (checkedKeys.value?.checked?.length == 0 || !chartObj.value?.kmdm)
    return createMessage.error('请选择要重置评阅进度的试题')
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () =>
      h('span', '点击确认后，仅当前选中的试题的评阅记录会进行重置，请再次确认是否执行该操作'),
    onOk: async () => {
      let { code, message } = await resetPyProcess({
        kmdm: Data.pageAccountCodeKmdm,
        resetAllFlag: false,
        stIdList: checkedKeys.value.checked,
      })
      if (code === 200) {
        createMessage.info('重置成功')
        checkedKeys.value.checked = []
        getRelseFun()
      } else {
        createMessage.error(message)
      }
    },
  })
}

// 打开设置弹窗
const handelRevocation = async row => {
  Data.isBatchHasObj = row
  Data.otherShowble = true
}

// 打开教师分配弹窗
const handelTeacher = async row => {
  Data.isBatchHasObj = row
  Data.teacherShowble = true
}

const chartObj = <any>ref({})
const sjlbList = ref<any>([])
// 是否发布试卷
const statuTypeBloon = ref(false)
/**
 * 统计数据
 * */
const getRelseFun = async () => {
  if (!Data.pageAccountCodeKmdm || Data.pageAccountCodeKmdm === '0') return
  let { code, data, message } = await getAcountmdm({
    kmdm: Data.pageAccountCodeKmdm,
  })
  if (code == 200) {
    chartObj.value = data
    statuTypeBloon.value = 'TEST,FORMAL,OVER_FORMAL,OVER_TEST'.includes(chartObj.value.kmpyjd)
    reset()
  } else {
    createMessage.error(message)
  }
}

/**
 * 获取系统配置
 *
 *  */
const sysConfig = computed(() => userStore.getSysConfig)

// 查询科目列表
const kmOptions = ref<any>([])
function filterOption(input: string, option: any = {}) {
  return option['kmmc']?.indexOf(input) >= 0
}

// 页面初始化
async function pageInit() {
  if (!userInfo.value.manageKmdm || userInfo.value.manageKmdm === '0') {
    let { code, data } = await getKmSimpAlleList({
      pageSize: 0,
    })
    if (code == 200) {
      data.forEach(item => (item.kmmc = `${item.kmdm}(${item.kmmc})`))
      kmOptions.value = data.sort((a, b) => a.kmdm - b.kmdm)
    }
  } else {
    Data.pageAccountCodeKmdm = userInfo.value.manageKmdm
  }
}

// 数据字典
import { getDictionaryList } from '/@/views/teacher/home/index'
import { router } from '/@/router'
watch(
  () => Data.pageAccountCodeKmdm,
  val => {
    if (!!val && val !== '0') {
      defaultFilterOption.kmdm = val
      treedataObj.value = {}
      list.value = []
      chartObj.value = {}
      getRelseFun()
    }
  },
  {
    immediate: true,
  }
)

// 修改试题结构
function modifyStructure() {
  if (!!Data.pageAccountCodeKmdm && Data.pageAccountCodeKmdm !== '0') {
    router.push({
      path: '/examination-audit/modifyStructure',
      query: {
        kmdm: Data.pageAccountCodeKmdm,
        sjlb: chartObj.value.sjlb,
      },
    })
  } else {
    createMessage.warning('请选择科目')
  }
}

onMounted(async () => {
  getDictionaryList('sjlb', sjlbList)
  pageInit()
})
</script>

<style lang="less" scoped>
.layout-card {
  min-height: calc(@c_height + 32px);

  .topClose {
    margin: 10px 0;

    thead tr th {
      text-align: center;
      border: 1px solid #e8e8e8;
      line-height: 60px;
      background-color: #eff6ff;
      width: 25%;
      white-space: nowrap;
    }
    thead tr th:nth-child(1) {
      width: 50%;
    }
    thead tr th:nth-child(n + 3) {
      width: 12.5%;
    }

    tbody tr td {
      text-align: center;
      border: 1px solid #e8e8e8;
      line-height: 60px;
      width: 12.5%;
    }

    ::v-deep(.ant-select-selector) {
      // border: none;
      background-color: #eff6ff;
      text-align: left;
      // .ant-select-selection-item {
      //   color: #d43030;
      // }
    }

    ::v-deep(.ant-select-arrow) {
      // color: #d43030;
    }
  }

  .claserbox {
    border: 1px solid #e8e8e8;
    margin-top: 10px;
    .infobox {
      width: 100%;
      height: calc(100vh - 400px);
      min-height: 200px;
      border-left: 1px solid #e8e8e8;
      padding: 10px;
      overflow-y: auto;
      font-size: 15px;
      .treebox {
        height: calc(100% - 50px);
        overflow-y: auto;
        ::v-deep(.ant-tree-checkbox-disabled .ant-tree-checkbox-inner) {
          background-color: #e8e8e8;
        }
        ::v-deep(.ant-tree-checkbox-inner) {
          border: 2px solid #d9d9d9;
        }
      }

      .allbutton {
        margin: 8px 8px 0 0;
      }
    }
  }
}
</style>
